#ifndef P2P_BASE_PORTALLOCATORSESSIONPROXY_H_
#define P2P_BASE_PORTALLOCATORSESSIONPROXY_H_

#include <string>
#include "candidate.h"
#include "portallocator.h"

namespace cricket
{
	class PortAllocatorSessionProxy;

	// This class maintains the list of criciet::Port* objects. Ports will be
	// deleted upon receiving SignalDestroyed signal. This class is used when
	// PORTALLOCATOR_ENABLE_BUNDLE flag is set.
	class PortAllocatorSessionMuxer : public base::MessageHandler, public sigslot::has_slots<>
	{
	public:
		explicit PortAllocatorSessionMuxer(PortAllocatorSession* session);
		virtual ~PortAllocatorSessionMuxer();

		void RegisterSessionProxy(PortAllocatorSessionProxy* session_proxy);

		void OnPortReady(PortAllocatorSession* session, PortInterface* port);
		void OnPortDestroyed(PortInterface* port);
		void OnCandidatesAllocationDone(PortAllocatorSession* session);

		const std::vector<PortInterface*>& ports() { return ports_; }

		sigslot::signal1<PortAllocatorSessionMuxer*> SignalDestroyed;

	private:
		// Port will be deleted when SignalDestroyed received, otherwise delete
		// happens when PortAllocatorSession dtor is called.
		base::Thread* worker_thread_;
		std::vector<PortInterface*> ports_;
		base::scoped_ptr<PortAllocatorSession> session_;
		std::vector<PortAllocatorSessionProxy*> session_proxies_;
		bool candidate_done_signal_received_;
	};


	class PortAllocatorSessionProxy : public PortAllocatorSession
	{
	public:
		PortAllocatorSessionProxy(const std::string& content_name, 
			int component, uint32 flags)
			: PortAllocatorSession(content_name, component, "", "", flags),
			impl_(NULL)
		{
		}
		virtual ~PortAllocatorSessionProxy();

		PortAllocatorSession* impl() { return impl_; }
		void set_impl(PortAllocatorSession* session);

		// Forwards call to the actual PortAllocatorSession.
		virtual void GetInitialPorts();
		virtual void StartGetAllPorts();
		virtual void StopGetAllPorts();
		virtual bool IsGettingAllPorts();

		virtual void set_generation(uint32 generation)
		{
			ASSERT(impl_ != NULL);
			impl_->set_generation(generation);
		}

		virtual uint32 generation()
		{
			ASSERT(impl_ != NULL);
			return impl_->generation();
		}

	private:
		void OnPortReady(PortAllocatorSession* session, PortInterface* port);
		void OnCandidatesReady(PortAllocatorSession* session,
			const std::vector<Candidate>& candidates);
		void OnPortDestroyed(PortInterface* port);
		void OnCandidatesAllocationDone(PortAllocatorSession* session);

		// This is the actual PortAllocatorSession, owned by PortAllocator.
		PortAllocatorSession* impl_;
		std::map<PortInterface*, PortProxy*> proxy_ports_;

		friend class PortAllocatorSessionMuxer;
	};
}

#endif	// P2P_BASE_PORTALLOCATORSESSIONPROXY_H_